// index.js
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Page({
  data: {
    userInfo: {
      imageUrl: defaultAvatarUrl,
      username: ""
    },
    code: ''
  },
  // 获取用户信息
  getUserInfo(code) {
    let data = this.data.userInfo
    wx.request({
      url: `http://127.0.0.1:8080/wechat/login?code=${code}`,
      method: "POST",
      header: {
        'content-type': 'application/json'
      },
      success(res) {
        data = res.data.data
        if (data) {
          wx.setStorageSync('userInfo', data)
          wx.showToast({
            title: '登录成功',
            duration: 800
          })
          setTimeout(() => {
            wx.switchTab({
              url: '/pages/my/my',
            })
          }, 1000)
        } else {
          wx.showToast({
            title: '登录失败',
            icon: 'none'
          });
        }
      },
      fail(err) {
        wx.showToast({
          title: '登录失败',
          icon: 'none',
          duration: 2000
        });
      }
    })
  },
  //授权登录
  authLogin() {
    const that = this
    wx.login({
      success: (res) => {
        that.getUserInfo(res.code)
      },
    })
  }
})